<?php
/**
 * Created by PhpStorm.
 * User: 34673
 * Date: 2020/5/12
 * Time: 9:44
 */

namespace app\api\controller;

use think\admin\Controller;
use PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\App;

class BaseController extends Controller
{

    public function _prepare_qiye_page_info($type, $kw,$limit=5){
        $total = $this->app->db->name($this->table)
            ->where(array("type"=>$type))
            ->whereLike("name","%".$kw."%")->count();
        $page = $this->request->get("page",1);
        return array(
            "limit" => $limit,
            "page" => $page,
            "total" => $total,
            "offset" => ($page-1)*$limit
        );
    }

    //准备分页信息
    public function _prepare_product_page_info($kw,$limit=5){
        $total = $this->app->db->name($this->table)
            ->whereLike("name","%".$kw."%")->count();
        $page = $this->request->get("page",1);
        return array(
            "limit" => $limit,
            "page" => $page,
            "total" => $total,
            "offset" => ($page-1)*$limit
        );
    }

    public function _get_link(){
        return $this->link = $this->app->db->name('CmsLink')->order("sort desc,id desc")->select();
    }

    protected function _inc_read_num($article_id){
        $map['id'] = $article_id;
        $this->app->db->name('CmsArticles')->where($map)->inc("read_num")->update();
    }

    //导航条信息
    protected function _get_nav_menus(){
        $arr = array();
        $this->mlist = $this->app->db->name('CmsMenu')->order('sort desc,id desc')->select()->toArray();
        for($i=0; $i<count($this->mlist); $i++){
            // var_dump($this->mlist[$i]['parent_id']);
            if($this->mlist[$i]['parent_id']==0){
                $this->mlist[$i]['sub'] = array();
                $arr[$this->mlist[$i]['id']] = $this->mlist[$i];
            }
        }
        for($i=0; $i<count($this->mlist); $i++){
            if($this->mlist[$i]['parent_id']>0){
                //$arr[$this->mlist[$i]['parent_id']]['sub'][] = $this->mlist[$i];
                array_push($arr[$this->mlist[$i]['parent_id']]['sub'], $this->mlist[$i]);
            }
        }
        $this->nav = $arr;
    }

    //读取配置文件
    protected function _system(){
        $this->link = $this->_get_link();
        $map = ["type" =>"contact"];
        $this->tlist = $this->app->db->name('SystemConfig')->where($map)->select();
        foreach ( $this->tlist as $name => $value)
            sysconf($name, $value);
    }

    //准备分页信息
    public function _prepare_page_info($category_id, $limit=5,$keyword=""){
        $page = $this->request->get("page",1);
        $total = $this->_get_category_articles_total($category_id,$keyword);
        return array(
            "limit" => $limit,
            "page" => $page,
            "total" => $total,
            "offset" => ($page-1)*$limit
        );
    }

    //准备分页信息
    public function _format_page_info($total, $limit=5){
        $page = $this->request->get("page",1);
        return array(
            "limit" => $limit,
            "page" => $page,
            "total" => $total,
            "offset" => ($page-1)*$limit
        );
    }

    //根据ID查询Category的信息
    public function _get_category($category_id){
        $map = array("status"=>1,"id"=>$category_id);
        return $this->app->db->name('CmsCategory')->field("id,title,type,is_private")->where($map)->find();
    }

    //根据ID查询子Category的信息
    public function _get_sub_category($category_id, $type=null){
        $map = array("status"=>1,"parent_id"=>$category_id);
        if($type)   $map['type'] = $type;
        return $this->app->db->name('CmsCategory')->field("id,title")->where($map)->select()->toArray();
    }

    //根据ID读取文章的信息
    public function _get_article($id){
        $map = array("id"=>$id);
        return $this->app->db->name('CmsArticles')->where($map)->order("sort desc,id desc")->find();
    }

    //支持多分类查询，根据关键字查询，根据分类ID，查询文章信息（6条）
    public function _get_category_articles($category_id, $offset=0, $len=6,$keyword=""){

        $map = ["is_deleted"=>0];
        $query = $this->app->db->name('CmsArticles');
        if(is_array($category_id)){
            $query = $query->whereIn("category_id",$category_id);
        }else{
            $map['category_id'] = $category_id;
        }
        if($keyword){
            $query = $query->whereLike("title","%$keyword%");
        }
        return $query->where($map)->order("sort desc,id desc")->limit($offset,$len)->select();
    }

    //支持多分类查询，根据分类ID，查询文章信息数量
    public function _get_category_articles_total($category_id, $keyword=""){
        $query = $this->app->db->name('CmsArticles');
        if(is_array($category_id)){
            $query = $query->whereIn("category_id",$category_id);
        }else{
            $map['category_id'] = $category_id;
            $query = $query->where($map);
        }
        if($keyword){
            $query = $query->whereLike("title","%$keyword%");
        }
        return $query->count();
    }

    /**
     * 清除文件路径中的主机地址
     * @param $inputFileName
     * @return string
     */
    public function filerFilePath($inputFileName){
        $inputFileName = str_replace('https://','',$inputFileName);
        $inputFileName = str_replace('http://','',$inputFileName);
        $inputFileName = str_replace($_SERVER['HTTP_HOST'],'',$inputFileName);
        return $_SERVER['DOCUMENT_ROOT'].$inputFileName;
    }

    public function _generate_enroll_no($student){
        $data = array(
            "idno" => $student['idno'],
            "name" => $student['name'],
            "phone" => $student['phone'],
        );
        return $this->app->db->name("CmsEduEnrollNo")->insertGetId($data);
    }

    public function getImportDataFromExcel($inputFileName, $fields, $startRow=2){
        $reader = PhpSpreadsheet\IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($inputFileName); //载入excel表格

        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数

        $result = array();
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return $result;
        }

        for ($row = $startRow; $row <= $highestRow; ++$row) {
            $data = array('update_at' => time());
            for($i=0; $i<count($fields); $i++){
                $data[$fields[$i]] = $worksheet->getCellByColumnAndRow($i+1, $row)->getValue();
            }
            $result[] = $data;
        }
        return $result;
    }

}